const Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:8545'));
const private_key = '0xb9a2cc97715ca2faad216e482fe6a990d2e46ec1fa9d81eba9ee51f7e266e52b';
// root
const eth_address = '0x39E5b8AC05972A67C97197f964674f278E04f349';
const fs = require('fs');
const contractJson = JSON.parse(fs.readFileSync('/home/fredyvia/digital-identity-management/build/contracts/DigitalIdentityManagement.json', 'utf8'));
const contractAbi = contractJson.abi;
const contractAddr = contractJson.networks['5777'].address;
console.log(contractAddr);
var contract = new web3.eth.Contract(contractAbi, contractAddr, { from: eth_address });

function sha256(data) {
  return crypto.createHash('sha256').update(data).digest()
}

const express = require('express');
var orm = require('orm');
const random = require('string-random');
const { MerkleTree } = require('merkletreejs')
const crypto = require('crypto')

const app = express();
const port = 3000;
app.use(orm.express('sqlite://./main.db', {
  define: function (db, models, next) {
    models.main = db.define('main', {
      address: { type: 'text', key: true },
      username: { type: 'text' },
      id: { type: 'text' },
      sex: { type: 'text' },
      phoneNum: { type: 'text' },
      salt_seed: { type: 'text' },
      merkle_root: { type: 'text' },
      merkle_index: { type: 'text' },
      merkle_root_signature: { type: 'text' }
    });
    next();
  }
}));
app.use(express.static('../frontend/build'));
app.use(express.json())
const sep = ':'
app.post('/submit', function (req, resp) {
  // res.send('Got a POST request');
  console.log(req.body);
  var item = req.body;

  item.address = item.address.toLowerCase();
  item.salt_seed = random(16);
  var salt = item.salt_seed;
  item.merkle_index = "username sex phoneNum address"
  var tmp_leaves = item.merkle_index.split(" ").map(attr => item[attr])
  console.log(tmp_leaves)
  var leaves = tmp_leaves.map(it => {
    salt = sha256(salt).toString("hex");
    return sha256(it + sep + salt);
  })

  console.log(leaves);
  const tree = new MerkleTree(leaves, sha256);
  item.merkle_root = tree.getRoot().toString('hex');
  console.log(item.merkle_root);
  var signature_object = web3.eth.accounts.sign(item.merkle_root, private_key);
  item.merkle_root_signature = signature_object.signature.toString('hex');
  schools = ["cqu", "scu", "uest", "tsinghua", "pku", "ustc"]
  item.id = schools[Math.floor(Math.random() * schools.length)];
  console.log(item);
  console.log("=====================")
  var current = new Date().getTime();
  var did = {
    userAddr: item.address,
    didMethodName: "edu",
    didId: item.id,
    issueDatetime: current,
    validDatetime: current + 100000000,
    issueDidSymbol: "cn:edu",
  };
  console.log(did);
  contract.methods.addDid(did).send({ gas: 10000000 }).then((error, res) => {
    console.error(error);
    console.log(res)
    req.models.main.create(item, function (err, items) {
      console.error(err)
      console.log(items)
    });
    resp.send('success');
  })

})

app.post('/list', function (req, res) {
  req.models.main.get(req.body.address.toLowerCase(), (error, main) => {
    console.log('======================');
    console.log(main);
    main.sep = sep;
    main.count = 4;
    main.method = 'edu';
    main.merkle_index = main.merkle_index.split(" ")
    console.log(error);
    res.send(main);
  });
})

app.listen(port, () => {
  console.log(`ca backend listening on port ${port}`);
})
